package com.zt.controller;

import com.zt.entity.Result;
import com.zt.pojo.MembershipOrder;
import com.zt.pojo.request.MembershipOrderRequest;
import com.zt.service.MembershipService;
import com.zt.enums.MembershipType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;

@RestController
@RequestMapping("/api/membership")
public class MembershipController {

    @Autowired
    private MembershipService membershipService;

    @PostMapping("/create")
    public Result createOrder(@RequestBody Map<String, Object> params) {
        try {
            // 从Map中提取参数并进行类型转换
            MembershipOrderRequest request = new MembershipOrderRequest();
            
            // 处理userId
            Object userIdObj = params.get("userId");
            if (userIdObj == null) {
                return Result.error("用户ID不能为空");
            }
            request.setUserId(Long.valueOf(userIdObj.toString()));
            
            // 处理membershipType
            Object typeObj = params.get("type");
            if (typeObj == null) {
                return Result.error("会员类型不能为空");
            }
            try {
                request.setType(MembershipType.valueOf(typeObj.toString()));
            } catch (IllegalArgumentException e) {
                return Result.error("无效的会员类型");
            }
            
            // 处理amount
            Object amountObj = params.get("amount");
            if (amountObj == null) {
                return Result.error("订单金额不能为空");
            }
            request.setAmount(Double.valueOf(amountObj.toString()));

            MembershipOrder order = membershipService.createOrder(request);
            return Result.success("创建会员订单成功", order);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("创建会员订单失败：" + e.getMessage());
        }
    }

    @GetMapping("/orders/{userId}")
    public Result getUserOrders(@PathVariable Long userId) {
        try {
            return Result.success("获取成功", membershipService.getUserOrders(userId));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取会员订单失败：" + e.getMessage());
        }
    }
} 